package com.waimai.app.qa.tool;

import java.util.Iterator;
import java.util.Map;

/**
 * 拼接生成.java文件中的内容
 * @author AiHui
 */
public class PagesGenerator{
    
	public static final String newLine = "\n";
	public static final String s1 = "/**\n * \n */\npackage com.waimai.app.qa.page;\n\nimport com.waimai.app.qa.data.Item;\nimport com.waimai.app.qa.data.PageObject;\nimport java.util.HashMap;\n\n/**\n * @author\n * \n */\n";
	public static final String s3 = "    // Declare variable\n";
	public static final String s5 = " public void init(HashMap<String, Object> items) {\n";
	public static final String s7 = "\t}\n}\n";

	public PagesGenerator(){
		
	}

    /**
     * 组合各个方法完成文本拼接
     * @param filesName
     * @param name
     * @return
     */
	public String generatePageClass(Map<String,String> filesName, String name){
		
		String sTitle = genTitle(name);
		String sDecl = "";
		String sInit = "";
		String sComm = "";
		String a[]=new String[3];
		
		Iterator<Map.Entry<String, String>> iterator = filesName.entrySet().iterator();
		while( iterator.hasNext()){   
			Map.Entry<String, String> entry = iterator.next();
			String varName = entry.getKey();
			String comm=entry.getValue();
			sComm=(new StringBuilder(String.valueOf(""))).append(genComm(comm)).toString();
			sDecl = (new StringBuilder(String.valueOf(sDecl))).append(sComm).append(genDecl(varName)).append(newLine).toString();
			sInit = (new StringBuilder(String.valueOf(sInit))).append(genInit(varName)).toString();
		}
		return (new StringBuilder(s1)).append(sTitle).append(sDecl).append(newLine).append(s5).append(sInit).append(s7).toString();
	}
    
	/**
	 * 生成java文件头
	 * @param name
	 * @return
	 */
	public static String genTitle(String name){
		//使用StringBuilder可以完成不定长度字符串的拼接，随时可以通过.append()方法增加内容
		return (new StringBuilder("public class ")).append(name).append(" implements PageObject {").append(newLine).toString();
	}
	
    /**
     * 生成java文件体：csv文件中的itemName
     * @param varName
     * @return
     */
	public static String genDecl(String varName){    
		return (new StringBuilder("\tpublic Item ")).append(varName).append(";").append(newLine).toString();
	}
     
	/**
      * 为itemName的每一项添加注释
      * @param varName
      * @return
      */
	public static String genComm(String varName){
		//通过varName获取value值，将value值解后存入数组。
		String[] a = varName.split("\\|"); 
		return(new StringBuilder("    /**")).append(newLine).append("    *@type ").append(a[0]).append(newLine).append("    *@testData ").append(a[1]).append(newLine).append("    *@locatorValue ").append(a[2]).append(newLine).append("    */").append(newLine).toString();
	}
	
	/**
	 * 生成java文件中init方法
	 * @param varName
	 * @return
	 */
	public static String genInit(String varName){
		return (new StringBuilder("\t\tthis.")).append(varName).append(" = (Item) items.get(").append('"').append(varName).append('"').append(");").append(newLine).toString();
	}
}
